﻿using Microsoft.EntityFrameworkCore;

namespace MicroBlog.Infrastructure
{
    /// <summary>
    /// 分页列表
    /// </summary>
    /// <typeparam name="T">T</typeparam>
    [Serializable]
    public class PagedList<T> : IPagedList<T>
    {
        /// <summary>
        /// Ctor
        /// </summary>
        /// <param name="source">source</param>
        /// <param name="pageIndex">Page index</param>
        /// <param name="pageSize">Page size</param>
        /// <param name="totalCount">Total count</param>
        public PagedList(IEnumerable<T> source, int pageIndex, int pageSize, int totalCount)
        {
            TotalCount = totalCount;
            TotalPages = TotalCount / pageSize;

            if (TotalCount % pageSize > 0)
                TotalPages++;

            this.PageSize = pageSize;
            this.PageIndex = pageIndex;
            this.DataSet = source.ToList();
        }
        public static async Task<IPagedList<T>> CreateAsync(IQueryable<T> source, int pageIndex, int pageSize)
        {
            var count = await source.CountAsync();
            var items = await source.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync();
            return new PagedList<T>(items, pageIndex, pageSize, count);
        }
        /// <summary>
        /// Page index
        /// </summary>
        public int PageIndex { get; }
        /// <summary>
        /// Page size
        /// </summary>
        public int PageSize { get; }
        /// <summary>
        /// Total count
        /// </summary>
        public int TotalCount { get; }
        /// <summary>
        /// Total pages
        /// </summary>
        public int TotalPages { get; }
        /// <summary>
        /// 上一页页码
        /// </summary>
        public int PreviousPage
        {
            get
            {
                return PageIndex > 1 ? PageIndex - 1 : 1;
            }
        }
        /// <summary>
        /// 下一页页码
        /// </summary>
        public int NextPage
        {
            get
            {
                return PageIndex < TotalPages ? PageIndex + 1 : TotalPages;
            }
        }
        /// <summary>
        /// Has previous page
        /// </summary>
        public bool HasPreviousPage
        {
            get { return (PageIndex > 1); }
        }
        /// <summary>
        /// Has next page
        /// </summary>
        public bool HasNextPage
        {
            get { return (PageIndex + 1 < TotalPages); }
        }
        /// <summary>
        /// 数据集
        /// </summary>
        public IList<T> DataSet { get; }
    }
}
